<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <div>
      <span>全选:</span>
      <input type="checkbox" v-model="isAll" />
      <button @click="reverseChecked">反选</button>
      <ul>
        <li v-for="v of arr" :key="v.name">
          <input type="checkbox" v-model="v.checked" />
          <span>{{ v.name }}</span>
        </li>
      </ul>
    </div>
  </div>
  <script src="./vue.js"></script>
  <script>

    // 在Vue全选和反选，用计算属性的完整写法实现

    const app = new Vue({
      el: '#app',
      data: {
        arr: [
          {
            name: "猪八戒",
            checked: false,
          },
          {
            name: "孙悟空",
            checked: false,
          },
          {
            name: "唐僧",
            checked: false,
          },
          {
            name: "白龙马",
            checked: false,
          },
        ],
      },
      computed: {
        // 是否全选，就看 arr 中每一个元素的 checked 是否为 true
        isAll: {
          get() {
            // 如果每一个都是true，则 every 函数返回值为 true，反之，为false
            return this.arr.every(v => v.checked)
          },
          set(newValue) {
            // 当全选框发生变化时，要影响每一个小选框，让小选框的选中状态和全选框的选中状态保持一致
            this.arr.forEach(v => {
              v.checked = newValue
            })
          }
        }
      },
      methods: {
        reverseChecked() {
          this.arr.forEach(v => {
            v.checked = !v.checked
          })
        }
      }
    })
  </script>


</body>

</html>